package web.service.impl;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import web.entity.User;
import web.mapper.RegisterMapper;
import web.service.RegisterService;
import web.utils.ResponseResult;

import java.util.List;

@Service
public class RegisterServiceImpl implements RegisterService {
    @Autowired
    private RegisterMapper registerMapper;

    @Override
    public ResponseResult register(User user) {
        if (isUserExist(user)) {
            return new ResponseResult(400, "用户名已存在!");
        }
        // 生成加密密码
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encode = bCryptPasswordEncoder.encode(user.getPassword());
        user.setPassword(encode);

        return registerMapper.register(user) == 1 ? new ResponseResult(200, "注册成功") : new ResponseResult(500, "注册失败");
    }

    @Override
    public List<User> selectUserByUserName(User user) {
        return registerMapper.selectUserByUserName(user);
    }

    @Override
    public Boolean isUserExist(User user) {
        List<User> users = selectUserByUserName(user);
        if (users.size() == 0) {
            return false;
        } else if (users.size() > 1) {
            throw new RuntimeException("存在同名用户.数据库错误");
        } else {
            return true;
        }
    }
}
